import CONSTANT from '../../constant';
import utils from '../../utils';

export default function(config, poster) {
    // 捕捉普通代码异常
    window.onerror = (message, url, lineNo, colNo, error) => {
        // 记录代码异常
        poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'code', message: encodeURIComponent(message), lineNo: lineNo, colNo: colNo, src: url, url:location.href, error: encodeURIComponent(JSON.stringify(error))});
    };
    // 捕捉Promise异常
    window.addEventListener('unhandledrejection', (event) => {
        if (event) {
            let reason = event.reason;
            if (!utils.isString(reason)) {
                reason = JSON.stringify(reason);
            }

            // 记录代码异常
            poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'unhandledRejection', message: encodeURIComponent(reason)});
            
        }
    }, true);

    window.addEventListener('error', (event) => {
        if (event) {
            const target = event.target || event.srcElement;
            const tagName = target.tagName;
            const isElementTarget = target instanceof HTMLScriptElement || target instanceof HTMLLinkElement || target instanceof HTMLImageElement;
            // js error不再处理
            if (!isElementTarget) return; 
            
            if (target) {
                const url = (target.src || target.href) || '';
                if (config.api && url.indexOf(config.api) < 0) {
                    // 记录代码异常
                    poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:tagName , message: encodeURIComponent(JSON.stringify(event).substring(0,500)), url:location.href, src: url});
                }        
            }
        }
    }, true);

    if (window.console && window.console.error) {
        window.console.error = (event) => {
            if (!utils.isString(event)) {
                event = JSON.stringify(event);
            }
            // 记录代码异常
            poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'console', message: encodeURIComponent(event)});
        };
    }

    if (!window.fetch) {
        if (!window.XMLHttpRequest) return;
        const originXhr = window.XMLHttpRequest;
        const originSend = originXhr.prototype.send;

        const handleEvent = (event) => {
            if (event) {
                if (event.currentTarget.status !== 200) {
                    // 记录代码异常
                    poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'xhr', message: encodeURIComponent(JSON.stringify(event))});
                }
            }
        };

        originXhr.prototype.send = function(args) {
            if (!this.addEventListener) {
                this.addEventListener('error', handleEvent);
                this.addEventListener('load', handleEvent);
                this.addEventListener('abort', handleEvent);
            } else {
                const originStateChange = this.onreadystatechange;
                this.onreadystatechange = (event) => {
                    if (this.readyState === 4) {
                        handleEvent(event);
                    }
                    originStateChange && originStateChange.call(this, event);
                };
            }
            return originSend.apply(this, args);
        };
    } else {
        const originFetch = window.fetch;
        window.fetch = (input, init) => {
            const fetchReq = originFetch.call(window, input, init);
            fetchReq.then(res => {
                if (!res.ok) {
                    // 记录代码异常
                    poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'fetch', message: encodeURIComponent(JSON.stringify(res))});
                }
            }).catch(error => {
                // 记录代码异常
                poster.sendDataByImg({uuid:CONSTANT.uuid, type:'error', subType:'fetch', message: encodeURIComponent(JSON.stringify(error))});
                throw error;
            });
            return fetchReq;
        };
    }    
    
}